<?php

class shopModel extends commonModel
{

    public function __construct()
    {
        $this->initialDB();
    }


    #订单的最后一笔指派单
    public function getLastExpressOrder($orderid)
    {

        $sql = " SELECT * FROM `orders_express` WHERE `isdeleted` = 0 AND orders_id='" . $orderid . "' AND (`status`=1 OR `status`=0) ORDER BY `createdt` LIMIT 0,1 ";
        $this->db->setStatement($sql);
        $result = $this->db->execute();
        $result = $this->getArray($result);

        return $result;
    }

    /*
     * 门店取消指派, express_status=7
     */
    public function cancel_order($express_type, $shop_express_no,$express_order_no,$cancel_code,$cancelInfo,$shop_no,$order_no)
    {
        $config = Config::getInstance();
        $website_array = $config->getWebSiteConfig();
        $express_status = 8;
        $cancel_result = array("result_code" => "-1", "express_code" => '-1', "express_code_desc" => '接口失败');
        $iscancel = false;
        $_data= array('shop_express_no' => $shop_express_no, 'express_type' => $express_type,'express_order_no'=>$express_order_no,'order_no'=>$order_no);
        $data_id = $this->addExpressData($_data, $express_status);

        # 获取分司快递参数
        $where_fields = array("AND" => array("=" => array('store_id' => $shop_no)));
        $store = $this->getItemByOther($where_fields,'xd_store');
        $where_fields_company = array("AND" => array("=" => array('code' => $store[0]['company_id'])));
        $company = $this->getItemByOther($where_fields_company,'xd_company');
        if ($express_type == "sf") {
            $sfe = new SFExpressClass($website_array['debug'],$company[0]['sf_dev_key'],$company[0]['sf_dev_id'],$company[0]['sf_user_name']);
            $info = $sfe->cancel($shop_express_no,$shop_no);
            $info = array_merge($info, $cancel_result);
            if ($info['error_code'] == 0) {
                $info['result_code'] = 0;
                $info['express_code'] = $info['error_code'];
                $info['express_code_desc'] = $info['error_msg'];
//                $iscancel = true;
                $iscancel = [true,'操作成功'];
            } else {
                $info['express_code_desc'] = $info['error_data']['desc'];
                $iscancel = [false,'操作失败'];
            }
        } elseif ($express_type == "ss") {
            $sse = new SSExpressClass($website_array['debug'],$store[0]['ss_clientId'],$store[0]['ss_clientSecret'],$store[0]['ss_shopId']);
            $parameter['issOrderNo'] = $express_order_no;
            $parameter['orderNo'] = $shop_express_no;
            $info = $sse ->cancel($parameter);
            $info = array_merge($info, $cancel_result);
            if ($info['status'] == 200) {
                $info['result_code'] = 0;
                $info['express_code'] = $info['status'];
                $info['express_code_desc'] = $info['msg'];
//                $iscancel = true;
                $iscancel = [true,'操作成功'];
            } else {
                $info['express_code_desc'] = $info['msg'];
                $iscancel = [false,'操作失败'];
            }
        } elseif ($express_type == "dd")  {
            $dde = new DDExpressClass($website_array['debug'],$store[0]['dd_source_id'],$store[0]['dd_app_key'],$store[0]['dd_app_secret']);
            $parameter = [
                'order_id' => $shop_express_no,
                'cancel_reason_id' => $cancel_code,
            ];
            if($cancel_code == 10000){
                $parameter['cancel_reason'] = $cancelInfo;
            }
            $info = $dde->formalCancel($parameter);
            if($info && $info['status'] == 'success'){
                $info = array_merge($info, $cancel_result);
                $info['result_code'] = 0;
                $info['express_code'] = $info['code'];
                $info['express_code_desc'] = $info['msg'];
//                $iscancel = true;
                $iscancel = [true,'操作成功'];
            } else {
                if($info == false){
                    $info = $cancel_result;
                    $info['express_code_desc'] = '达达请求失败';
                    $iscancel = [false,'未知状态'];
                }else{
                    $info = array_merge($info, $cancel_result);
                    $info['express_code_desc'] = $info['msg'];
                    $iscancel = [false,$info['msg']];
                }
            }

        }elseif ($express_type == "jrd"){
            $JRD = new JRDExpressClass($website_array['debug'],$store[0]['jrd_sign']);
            $parameter = [
                'order_no' => $express_order_no,
            ];
            $info = $JRD->formalCancel($parameter);
            if($info && $info['error_code'] == 0){
                $info = array_merge($info, $cancel_result);
                $info['result_code'] = 0;
                $info['express_code'] = $info['error_code'];
                $info['express_code_desc'] = $info['error_msg'];
                $iscancel = [true,'操作成功'];
            } else {
                $info['express_code_desc'] = $info['error_msg'];
                $iscancel = [false,'操作失败'];
            }
        }elseif ($express_type == "uu"){
            $uue = new UUExpressClass($website_array['debug'],$store[0]['uu_app_id'],$store[0]['uu_app_key'],$store[0]['uu_open_id']);

            $parameter = [
                'origin_id' => $shop_express_no,
                'reason' => $cancelInfo ? $cancelInfo : '操作错误',
            ];
            $info = $uue->cancelorder($parameter);
            if($info && strtolower($info['return_code']) == 'ok'){
                $info = array_merge($info, $cancel_result);
                $info['result_code'] = 0;
                $info['express_code'] = $info['return_code'];
                $info['express_code_desc'] = $info['return_msg'];
                $iscancel = [true,'操作成功'];
            } else {
                $info['express_code_desc'] = $info['return_msg'];
                $iscancel = [false,'操作失败'];
            }
        }elseif ($express_type == "slw"){
            $SLW = new SLWExpressClass($website_array['debug'],$store[0]['user365Id']);
            $data['shop_no'] = $shop_no;
            $data['user365Id'] = $store[0]['user365Id'];
            $data['365pwd'] = $store[0]['365pwd'];
            $data['365serviceKey'] = $store[0]['365serviceKey'];
            $row = new SLWTokenClass($website_array['debug'],$this);
            $token = $row->token();
            $parameter = [
                'orderId' => $express_order_no,
                'token' => $token,
            ];
            $info = $SLW->cancelOrder($parameter);
            if($info && strtolower($info['errorcode']) == 0){
                $info = array_merge($info, $cancel_result);
                $info['result_code'] = 0;
                $info['express_code'] = $info['errorcode'];
                $info['express_code_desc'] = $info['message'];
                $iscancel = [true,'操作成功'];
            } else {
                $info['express_code_desc'] = $info['message'];
                $iscancel = [false,'操作失败'];
            }
        }

        $this->updateExpressData($data_id, $info);
        return $iscancel;
    }

    public function judgeExp($xd_company,$express_type){
        $where = array('AND'=>array('='=>array('store_id'=>$_SESSION['zp_shop']['store_id'])));
        $shops = $this->getItemByOther($where,'xd_store');

        if($express_type == 'sf'){
            if($xd_company[0]['sf_user_name'] == '' || $xd_company[0]['sf_dev_key'] == '' || $xd_company[0]['sf_dev_id'] == ''){
                return false;
            }
        }elseif($express_type == 'ss'){
            if(!$shops[0]['phone']){
                return false;
            }
            if($shops[0]['ss_clientId'] == '' || $shops[0]['ss_clientSecret'] == '' || $shops[0]['ss_shopId'] == ''){
                return false;
            }
        }elseif ($express_type == 'dd'){
//            $shops = $this->getItemByOther($where,'xd_store');
            if(!$shops[0]['phone']){
                return false;
            }
            if($shops[0]['dd_source_id'] == '' || $shops[0]['dd_app_secret'] == '' || $shops[0]['dd_app_key'] == ''){
                return false;
            }
        }elseif($express_type == 'jrd'){
//            $shops = $this->getItemByOther($where,'xd_store');
            if($shops[0]['jrd_sign'] == ''){
                return false;
            }
        }elseif($express_type == 'slw'){
            if($shops[0]['user365Id'] == ''){
                return false;
            }
        }elseif($express_type == 'uu'){
            if($shops[0]['uu_app_id'] == '' || $shops[0]['uu_app_key'] == '' || $shops[0]['uu_open_id'] == ''){
                return false;
            }
        }
        return true;
    }


    public function getStatusTotal($status) {
        $storeNo = $_SESSION['zp_shop']['store_id'];
        if($status < 6){
            $w = " status = $status";
        }else{
            $w = " (`status`=6 OR `status` = 7) ";
        }
        $sql = " SELECT count(id) as count FROM orders WHERE isdeleted=0  AND shop_no=$storeNo AND $w";
        $this->db->setStatement($sql);
        $result= $this->db->execute();
        $result=$this->getArray($result,'one');
        $count=0;
        if (!empty($result)){
            $count=$result['count'];
        }
        return $count;

    }


    public function GetOrdersDataNew($flag,$page, $number_page,$where ) {
        if (is_null($page)) {
            $page = 1;
        }
        if (is_null($number_page)) {
            $number_page = 10;
        }
        $offset = ($page - 1) * $number_page;


        $limit=' LIMIT '.$offset.', '.$number_page;

        $LEFT = " LEFT JOIN  shop_delivery_address as sda ON sda.orders_id = o.id and sda.isdeleted = 0";
        $field = "sda.receiver_name as sda_receiver_name ,sda.receiver_tel as sda_receiver_tel,sda.receiver_address as sda_receiver_address,sda.lat as sda_lat ,sda.lng as sda_lng,sda.distance as sda_distance,sda.id as sda_id";
        $field .= ",o.id,o.order_no,o.shop_no,o.ph_no,o.distance,o.lng,o.lat,o.pos_fee,o.buyer,o.receiver,o.receiver_tel,o.receiver_address,o.delivery_time,o.customre_memo,o.seller_remarks,o.status,o.buyer_mobile ,o.express_type ";

        if ($flag=='all'){
            $field=' count(o.id) as count ';
            $limit='';
        }
        $sql = "SELECT $field FROM orders as o $LEFT WHERE $where order by delivery_time asc ".$limit;

//        ORDER BY online asc , p.updatedt desc ".$limit."
//         echo $sql;

        $this->db->setStatement($sql);
        $result= $this->db->execute();
        $result=$this->getArray($result);
        return $result;
    }



    public function GetOrdersData($page,$number_page,$sql){
        $total_count = $this->getTotalCountByJoinID($sql);


        $res = $this->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        $rsp_list = [];
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        return $data = ['rsp_page_list'=>$rsp_page_list,'rsp_list'=>$rsp_list,'total_count'=>$total_count];

    }


    public function EditShopDateilsAddressStatus($id,$orders_id) {
        $sql = "update shop_delivery_address set isdeleted=1  WHERE  status = '1' AND orders_id = $orders_id AND id != $id";
        $this->db->setStatement($sql);
        $result= $this->db->execute();
    }
}
